<template>
  <div>
    <el-card shadow="never" class="aui-card--fill" :style="searchShow?'margin-top: 10px;':''">
      <el-col>
        <el-button size="small" type="primary" @click="addRow()">{{ $t('add') }}</el-button>
        <el-button size="small" type="primary" @click="openSelCol()">{{ '从字段库添加' }}</el-button>
      </el-col>
      <el-col :style="'margin-top: 10px; margin-bottom: 30px;'">
        <div class="mod-dpd__dpdTableColumns">
          <vxe-table ref="editable" v-loading="loading" :showOverflow="false" row-key :data="dataList" class="vxe-table-element"
            border :edit-config="{trigger: 'click', mode: 'row' }" :edit-rules="dataRule" auto-resize>
            <vxe-table-column type="index" fixed="left" width="50" align="center"></vxe-table-column>
            <vxe-table-column width="60" align="center">
              <template>
                <span class="drag-btn">
                  <i class="vxe-icon--menu"></i>
                </span>
              </template>
              <template v-slot:header>
                <vxe-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
                  <i class="vxe-icon--question" @click="showHelpTip1 = !showHelpTip1"></i>
                </vxe-tooltip>
              </template>
            </vxe-table-column>
            <!-- 字段名称 -->
            <!--文本框-->
            <vxe-table-column field="columnName" title="字段名称" :edit-render="{name: 'ElInput', autofocus:false, props: {clearable:true}}"
              min-width="150">
              <!-- <template v-slot:edit="{ row }">
                <el-autocomplete class="inline-input" v-model="row.columnName" popper-class="uniedp-autocomplete"
                  clearable value-key="columnName" :fetch-suggestions="querySearch" placeholder="请输入内容"
                  :trigger-on-focus="false" @select="(item)=>{handleSelect(item,row)}">
                  <template slot-scope="{ item }">
                    <div class="name" v-if="item.columnComment">{{ item.columnComment }}</div>
                    <span class="addr">{{ item.columnName + '('+item.columnType+')'}}</span>
                  </template>
                </el-autocomplete>
              </template> -->
            </vxe-table-column>
            <!-- 字段类型 -->
            <!--文本框-->
            <vxe-table-column field="columnTypeBiz" title="业务类型" :edit-render="{name: 'ElInput',autofocus:false}" width="150">
              <template v-slot:edit="{ row }">
                <UniFieldSelect v-model="row.columnTypeId" :data="fieldTypeList" :backFun="(outRow)=>{ backFun (row, outRow) }"></UniFieldSelect>
              </template>
            </vxe-table-column>
            <vxe-table-column field="columnType" title="字段类型" :edit-render="{name: 'ElInput',autofocus:false}" width="130">
              <template v-slot:edit="{ row }">
                <el-input v-model="row.columnType" placeholder="字段类型" clearable :readonly="row.limitFlag"></el-input>
              </template>
            </vxe-table-column>
            <!-- 长度 -->
            <!--文本框-->
            <vxe-table-column field="maxLength" title="长度" :edit-render="{name: 'ElInput',autofocus:false}" width="100"
              align="center">
              <template v-slot:edit="{ row }">
                <el-input v-model="row.maxLength" clearable :readonly="row.limitFlag"></el-input>
              </template>
            </vxe-table-column>
            <!-- 小数位数 -->
            <!--文本框-->
            <vxe-table-column field="numericScale" title="小数位数" :edit-render="{name: 'ElInput',autofocus:false}" width="100"
              align="center">
              <template v-slot:edit="{ row }">
                <el-input v-model="row.numericScale" clearable :readonly="row.limitFlag"></el-input>
              </template>
            </vxe-table-column>
            <!-- 允许NULL -->
            <!--开关单选-->
            <vxe-table-column field="isNullable" title="允许NULL" :edit-render="{name: 'ElSwitch',autofocus:false, type: 'visible'}"
              width="100" align="center">
            </vxe-table-column>
            <!-- 默认值 -->
            <!--文本框-->
            <vxe-table-column field="columnDefault" title="默认值" :edit-render="{name: 'ElInput',autofocus:false, props: {clearable:true}}"
              width="100" align="center">
            </vxe-table-column>
            <!-- KEY类型 PRI主键 -->
            <!--下拉框-->
            <!-- <vxe-table-column field="columnKey" title="KEY类型" :edit-render="{name: 'ElSelect',
                         props:{clearable:true},
                         options:columnKeyList,
                         optionProps:{value: 'val', label: 'label' } }">
            </vxe-table-column> -->
            <!-- 字段备注 -->
            <!--文本框-->
            <vxe-table-column field="columnComment" title="字段备注" :edit-render="{name: 'ElInput', autofocus:false, props: {clearable:true}}"
              min-width="100">
            </vxe-table-column>
            <!-- 排序 -->
            <!--计数器-->
            <!-- <vxe-table-column field="sort" title="排序" :edit-render="{name: 'ElInputNumber',autofocus:false,props: {min: 1,max:50} }"
              width="100" align="center">
            </vxe-table-column> -->
            <vxe-table-column title="handle" header-align="center" align="center" width="70">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="deltRow(scope.row)">{{ $t('delete') }}</el-button>
              </template>
            </vxe-table-column>
          </vxe-table>
        </div>
      </el-col>
    </el-card>
    <dpdTableColumnsSee ref="refSee" v-if="dpdTableColumnsSeeVisable" :backFun="selColumnsBackFun"></dpdTableColumnsSee>
  </div>
</template>

<style>
@import './common/dpdStyle.scss';
.uniedp-autocomplete ul {
  width: 200px;
  padding: 5px 5px;
}
.uniedp-autocomplete li {
  width: 200px;
  padding: 0px 0px;
}
.uniedp-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
  height: 16px;
  line-height: 16px;
}
.uniedp-autocomplete li .addr {
  font-size: 12px;
  color: #b4b4b4;
  height: 12px;
  line-height: 12px;
}
.uniedp-autocomplete li .highlighted .addr {
  color: #ddd;
}
</style>

<script>
import mixinViewModule from '@/mixins/view-module'
import mixinViewSortable from './common/view-sortable'
import UniFieldSelect from '@/components/uni-field-select'
import $cons from './common/constant'
import dpdTableColumnsSee from './dpdTableColumns-see'

export default {
  mixins: [mixinViewModule, mixinViewSortable],
  data () {
    return {
      dpdTableColumnsSeeVisable: false,
      showHelpTip1: false,
      loading: false,
      fieldTypeList: [],
      columnKeyList: $cons.columnKeyList,
      mixinViewModuleOptions: {
        activatedIsNeed: false,
        getDataListURL: '/dpd/dpdTableColumns/list',
        getDataListIsPage: false,
        deleteURL: '/dpd/dpdTableColumns',
        deleteIsBatch: false
      },
      dataForm: {
        id: '',
        tableId: '',
        columnName: '',
        isNullable: true,
        columnDefault: '',
        columnType: '',
        columnTypeId: '',
        columnTypeBiz: '',
        limitFlag: false,
        maxLength: '',
        numericScale: '',
        columnKey: '',
        columnComment: '',
        sort: '',
        remark: '',
        creator: '',
        createDate: '',
        updater: '',
        updateDate: ''
      },
      deltList: [],
      dataRule: {
        columnName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        columnType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        columnComment: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        sort: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () { },
  components: { UniFieldSelect, dpdTableColumnsSee },
  methods: {
    openSelCol () {
      this.dpdTableColumnsSeeVisable = true
      this.$nextTick(() => {
        this.$refs.refSee.dataForm.dbType = this.dbType
        this.$refs.refSee.init()
      })
    },
    selColumnsBackFun (data) {
      let newRow = {
        ...this.dataForm,
        ...data,
        id: ''
      }
      this.$refs.editable.insertAt(newRow, -1)
    },
    querySearch (queryString, cb) {
      if (queryString != null && queryString.length > 0) {
        let results
        this.$http.get('/dpd/dpdColumn/columnPage', { params: { likeName: queryString } }).then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          results = res.data.list
          // 项目匹配字段超过5个待选项直接返回，否则继续添加平台字段
          if (results.length > 5) {
            cb(results)
            return
          }
          this.$http.get('/dpd/dpdColumn/page', { params: { likeName: queryString, dbType: this.dbType } }).then(({ data: res }) => {
            if (res.code !== 0) {
              return
            }
            results.concat(res.data.list)
            cb(results)
          })
        })
      }
    },
    handleSelect (item, row) {
      row.isNullable = item.isNullable
      row.columnDefault = item.columnDefault
      row.columnType = item.columnType
      row.columnTypeId = item.columnTypeId
      row.columnTypeBiz = item.columnTypeBiz
      row.limitFlag = item.limitFlag
      row.maxLength = item.maxLength
      row.numericScale = item.numericScale
      row.columnComment = item.columnComment
      this.$refs.editable.clearActived()
    },
    // 统一读取数据，不采用组件自动加载，可编辑table会创建多个副本
    async getFieldTypeList () {
      this.$http.get('/dpd/dpdColumnType/list', { params: { dbType: this.dbType } }).then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.fieldTypeList = res.data
      })
    },
    backFun (row, outRow) {
      row.columnType = outRow.columnType
      row.columnTypeBiz = outRow.columnTypeBiz
      row.limitFlag = outRow.limitFlag
      row.maxLength = outRow.maxLength
      row.numericScale = outRow.numericScale
    },
    // 新增
    addRow () {
      // 默认插入一行 可以设置插入数据的默认值 自行处理
      this.$refs.editable.insertAt(this.dataForm, -1).then(row => {
        // 设置插入行的可编辑状态
        this.$refs.editable.setActiveRow(row)
      })
    },
    getAllData () {
      return this.$refs.editable.getTableData().tableData
    },
    // 删除row
    deltRow (rowData) {
      // 主键是否为空
      if (rowData.id) {
        // 不为空将 row 移到 deltList
        this.deltList.push(rowData)
        // 移除行
        this.$refs.editable.remove(rowData)
      } else {
        this.$refs.editable.remove(rowData)
      }
    },
    async fullValidEvent () {
      const errMap = await this.$refs.editable.fullValidate().catch(errMap => errMap)
      let self = this
      if (errMap) {
        Object.values(errMap).forEach(errList => {
          errList.forEach(params => {
            let { rowIndex, column, rules } = params
            rules.forEach(rule => {
              self.$message.error(`第 ${rowIndex} 行 ${column.title} 校验错误：${rule.message}`)
            })
          })
        })
        return false
      } else {
        return true
      }
    }
  }
}
</script>
